package zdream.pmfield.stage.buff.ailment;

import zdream.pmfield.data.foe.MoveAdditionalEffects;
import zdream.pmfield.data.foe.Type;
import zdream.pmfield.stage.buff.foe.FoeStageBuff;
import zdream.pmfield.stage.buff.seat.SeatStageBuff;
import zdream.pmfield.stage.director.AttackContext;
import zdream.pmfield.stage.director.FixPair;
import zdream.pmfield.stage.director.HookType;
import zdream.pmfield.stage.director.Hooks;
import zdream.pmfield.stage.object.FoeActor;

/**
 * 在飞行状态下:
 * <li>每次轮次开始时, 行动判定多一个骰子 (最多每轮 +3 移动点)
 * <li>免疫某些特定的砂系 (原地面系) 技能. 免疫效果不在这个 buff 里面写
 * <li>免疫某些特定的 {@link SeatStageBuff} 影响.
 * <li>被 {@link Type#ELECTRIC} 或者 {@link Type#ICE} 攻击时,
 * {@link Type#SAND} 对 {@link Type#ELECTRIC} 的免疫失效,
 * 并额外增加权重为 0.5 的效果拔群.
 * </li>
 *
 * @author Zdream
 * @date 2023-12-03
 * @since 0.0.1
 */
public class FlyingBuff extends FoeStageBuff {
	public static final String CATEGORY = MoveAdditionalEffects.E_FLYING;

	public FlyingBuff(FoeActor target) {
		super(target);
	}

	@Override
	public void init() {
		preventSameBuffBeforeFoeReceiveBuff();
		onHook(HookType.BEFORE_FOE_TURN_START)
				.handle(this::beforeTurnStart)
				.withPriority(-900)
				.buildAndSave();
		onHook(HookType.ON_CHECK_TYPE_FIXED)
				.handle(this::onCheckTypeFixed)
				.withPriority(-100) // 比 BuffFixedRateEffect 早
				.buildAndSave();
	}

	public void beforeTurnStart(Hooks.HookContext rawContext) {
		Hooks.BeforeTurnHookContext context = rawContext.as();
		if (context.foe != target) {
			return;
		}
		context.movePointRollCount += 1;
	}

	public void onCheckTypeFixed(Hooks.HookContext rawContext) {
		final Hooks.AttackHookContext hooks = rawContext.as();
		final AttackContext attackContext = hooks.attackContext;

		boolean moveIsElectricOrIce = attackContext.currentMove.hasType(Type.ELECTRIC)
				|| attackContext.currentMove.hasType(Type.ICE);
		if (!moveIsElectricOrIce) {
			return;
		}

		for (AttackContext.AttackContextItem item : attackContext.items) {
			if (item.targetFoe != target) {
				continue;
			}

			for (FixPair pair : item.typeFixPairs) {
				if (!pair.isForType()) {
					continue;
				}

				// 如果在空中, 砂对电的免疫失效
				final FixPair.TypeFixPair typePair = pair.asType();
				if (typePair.attack == Type.ELECTRIC && typePair.defense == Type.SAND) {
					typePair.fixRateLevel = 0;
				}
			}

			item.typeFixPairs.add(FixPair.ofDefenseBuff(0.5f, (byte) 1, CATEGORY));
		}
	}

	@Override
	public String getCategory() {
		return CATEGORY;
	}

	@Override
	public String toString() {
		return "飞行中";
	}
}
